package com.example.cardview

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.example.cardview.b.CardLayoutManager
import com.example.cardview.b.ItemTouchHelperCallback


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val list  = arrayListOf<Int>(
            Color.BLACK,
            Color.RED,
            Color.GREEN,
            Color.BLUE,
            Color.YELLOW,
            Color.GRAY,
            Color.DKGRAY,
            Color.CYAN,
        )



        val rv = findViewById<RecyclerView>(R.id.rv)
        val rootView = findViewById<ViewGroup>(R.id.rootView)

        rootView.post {
            val myAdapter = MyAdapter(this, list,rootView.height)
            rv.layoutManager = CardLayoutManager()
            rv.adapter = myAdapter

            val itemTouchHelperCallback = ItemTouchHelperCallback(list, myAdapter)
            val itemTouchHelper = ItemTouchHelper(itemTouchHelperCallback)
            itemTouchHelper.attachToRecyclerView(rv)
        }


    }



     class MyAdapter(private val mContext: Context, private val mStrings: List<Int>,val h:Int) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
        override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): MyViewHolder {
            val inflate =
                LayoutInflater.from(mContext).inflate(R.layout.item_recyclerview, viewGroup, false)
            val height = h - mContext.dp2Px(146f + 90 + 24)
            val layoutParams = inflate.layoutParams
            layoutParams.height = height
            inflate.layoutParams = layoutParams
            return MyViewHolder(inflate)
        }

        override fun onBindViewHolder(holder: MyViewHolder, i: Int) {
            holder.textView.text = "${mStrings[i]}"
            holder.viewG.setBackgroundColor(mStrings[i])
        }

        override fun getItemCount(): Int {
            return mStrings.size
        }

         inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var textView: TextView
            var viewG: ViewGroup

            init {
                textView = itemView.findViewById<TextView>(R.id.tv)
                viewG = itemView.findViewById<ViewGroup>(R.id.itemRoot)
            }
        }
    }


}